package com.chenwy.example;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.io.UnsupportedEncodingException;

public class GenerateToken {

    private Algorithm algorithm;

    private String secret;

    private String issuer;

    public GenerateToken(String secret,String issuer) throws UnsupportedEncodingException {
        this.secret = secret;
        this.issuer = issuer;
        algorithm = Algorithm.HMAC256(this.secret);
    }

    public String create(String user){
        String token = JWT.create().withIssuer(issuer).withClaim("user",user).sign(algorithm);
        return token;
    }

    public DecodedJWT verify(String token,long expired){
        try{
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(issuer).acceptExpiresAt(expired).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt;
        }catch(JWTVerificationException ex){
            return null;
        }
    }

}
